<template>
  <section>
    <div class="header-btn">
      <el-button @click="$emit('input',false)">取消</el-button>
      <el-button type="primary" @click="update">提交审核</el-button>
    </div>
    <el-form label-width="0" ref="ruleForm" :model="form" class="sms-form">
      <el-form-item
        label=""
        prop="applyContent"
        class="sms-form-content"
      >
        <el-input
          v-model="form.applyContent"
          class="textarea"
          placeholder="请输入模板内容"
          type="textarea"
          resize="none"
          @blur="textareaBlur"
          :rows="10">
        </el-input>
      </el-form-item>

      <!-- <el-form-item
        class="select-modules"
        :required="true">

        <el-form-item
          prop="selectModule"
          :rules="{ message: '请选择模块', trigger: 'change' }">

          <el-select
            v-model="form.selectModule"
            placeholder="选择模块"
            @change="moduleChange"
          >
            <el-option
              v-for="item in moduleList"
              :key="item.moduleId"
              :label="item.moduleName"
              :value="item.moduleId"
            >
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item
          prop="selectField"
          class="sms-form-field"
          :rules="{ message: '请选择字段', trigger: 'change' }">
          <el-select
            v-model="form.selectField"
            :filterable="moduleType === 'task' ? true : false"
            placeholder="选择字段"
          >
            <el-option
              v-for="(item, index) in fieldList"
              :key="index"
              :label="item.filedName || item.fieldName"
              :value="item.fieldValue"
            >
            </el-option>
          </el-select>
          <el-button type="text" class="insert-btn" @click="addField"> &lt/&gt 插入字段</el-button>
          <span class="tip"> <i class="iconfont icon-info-circle"></i>点击后可在内容所在光标位置插入字段</span>
        </el-form-item>

    </el-form>

    <div class="tips">
      模板填写规范<br/>
      1.模板内容可添加多个变量，变量格式由系统自动生成不可变更<br/>
      2.系统变量每种仅限使用一次<br/>
    </div>
  </section>
</template>

<script>

import { getTaskExtendFieldList } from '@src/api/TaskApi'
import { isSubForm } from '@src/util/function';
export default {
  name:'sms-form',
  inject: {
    module: { value: "module", default: null },
    flowData: { value: "flowData", default: null },
    projectData: { value: "projectData", default: null },
  },
  data(){
    return{
      loading:false,
      moduleList:[],
      fieldList:[],
      textareaBlurPos: 0, // textarea 失焦的位置
      form:{
        // 短信模版内容
        applyContent:'',
        // 选择的模块
        selectModule:'',
        // 选择的字段
        selectField:''
      }

    }
  },

  props:{
    value:{
      type:Boolean,
      required:true
    },
    // 消息模块的来源/ 客服/ 工单/ 智能报告
    moduleType: {
      type: String,
      default: '',
    },

    smsTemplate:{
      type:Object,
      required:true
    },

    // 当前渠道的channel值
    channel:{
      type:[String,Number],
      required:true
    },

    // 当前选中的渠道
    sendChannelList:{
      type:Array,
      required:true
    },
    modules: {
      type: Array,
      default: () => []
    },
    // 消息类型 inside：内部，customer：客户
    type: {
      type:String,
      required:true
    },

    // 当前的触发对象
    messageTriggerType: {
      type: String,
      default: '',
    },

    // 当前的触发对象的表单字段
    taskExtendData: {
      type: Array,
      default: (() => []),
    }
  },
  watch: {
    type: {
      handler() {
        // 消息通知切换内部外部数据初始化
        this.init()
      }
    }
  },
  mounted(){
    this.init()
  },
  methods:{
    async init() {
      const { usageSmsContent, approveSmsContent, notice } = this.smsTemplate
      this.form.applyContent =  approveSmsContent || usageSmsContent

      if (Array.isArray(this.modules) && this.modules.length) {
        this.moduleList = this.modules
        this.fieldList = this.modules[0]?.fieldList || []
        this.form.selectModule = this.modules[0]?.moduleId || this.modules[0]?.moduleValue || ''
      } else {
        await this.getTemplateFields(notice)
      }
      // 如果是工单中心的消息设置
        if (this.moduleType === 'task') {
        this.getTaskExtendField()
      }
    },

    getTaskExtendField() {
      getTaskExtendFieldList({type: 'TASK'}).then((res) => {
        if (res.succ && res.data?.fieldList?.length > 0) {
          this.fieldList = [...this.fieldList, ...res.data.fieldList]
        }
      })
    },

    textareaBlur(e) {
      this.textareaBlurPos = e.target.selectionStart
    },
    // 父组件调用,校验短信模版是否填写正确
    getApplyText(){
      const { applyContent } = this.form;
      const { notice = '' } = this.smsTemplate || {}
      if (notice.includes('含回访') && !applyContent.includes('{smsUrl}')) {
        return '短信回访模版必须包含链接地址 {smsUrl} 字段'
      }
      // 当前渠道是否被勾选了
      const isSelected = this.sendChannelList.includes(this.channel)
      // 如果是智能日报 也只需要校验sysCheckKeyMap字段，
      return applyContent ? true : `您${isSelected ? '勾选了' : '修改了'}短信消息渠道，请先填写短信模板内容`
    },

    addField(){
      const { selectModule, selectField, applyContent = ''} = this.form;
      const { textareaBlurPos } = this
      // 当没有选择模块和字段时提示选择
      if(!(selectModule && selectField)){
        this.$refs.ruleForm.validateField('selectModule');
        // this.$refs.ruleForm.validateField('selectField');
        this.$message.warning('请选择字段');
        return
      }
      if(applyContent.includes(selectField)) {
        const { filedName } = this.fieldList.find(item=>item.fieldValue == selectField);
        if (Array.isArray(this.modules) && this.modules.length) {
          return this.$message.warning('该字段已存在，请勿重复添加');
        }
        return this.$message.warning(`[${filedName}]该字段已存在，请勿重复添加`);
      }
      // 获取失焦后光标前后的字符串
      const beforeTxt = applyContent.substring(0, textareaBlurPos);
      const afterTxt = applyContent.substring(textareaBlurPos);

      this.form.applyContent = `${beforeTxt}{${ selectField }}${afterTxt}`;
    },

    async getTemplateFields(notice){
      // console.log(notice, this.flowData, 'fetch sms');
      if(this.module === 'paas') {
        this.form.selectModule = 'paas';
        this.fieldList = this.flowData.msgTemplateSelectFields.map(item =>({ ...item, filedName: item.fieldName}))
        return
      }

      // 项目管理模块处理
      if(this.module === 'project') {
        this.form.selectModule = 'project';
        if (this.messageTriggerType === 'TASK') {
          // 项目消息-任务消息列表字段处理 工单字段/通用字段
          this.fieldList = this.taskExtendData.filter(field => !isSubForm(field) && !field?.isHidden).map(item=> {
              return {
                fieldValue: item.fieldName,
                fieldName: item.displayName,
                moduleId: item.fieldName,
                moduleName: 'project'
              }
          })
          return
        }
        // 项目类型表单的字段
        return this.fieldList = this.projectData.fields.map(item =>({ ...item, filedName: item.fieldName}))
      }

      await this.$http.get('/vipsms/getTemplateFields', { template:notice }).then(res=>{
        if (res && res.status == 0 && res.data && res.data.length) {
          this.moduleList = res.data
          if(Array.isArray(res.data) && res.data.length > 0)  {
            this.fieldList = res.data[0].fieldList
            this.form.selectModule = res.data[0].moduleId;
          }
        }
      })
    },

    // 修改模块时，将当前模块的字段列表赋值给fieldList
    moduleChange (value) {
      this.form.selectModule = value;

      this.moduleList.map(item => {
        const { moduleId, fieldList } = item

        if(moduleId === this.form.selectModule){
          this.fieldList = fieldList || []
        }
      })
    },
    // 提交审核
    update(){
      const { id, name, notice, approveSmsContent, usageSmsContent } = this.smsTemplate
      const origin = approveSmsContent || usageSmsContent
      if(!this.form.applyContent) return this.$message.warning('请填写模板内容')
      // 判断模板内容是否有更新 如果没有更新就不提交审核
      if(origin === this.form.applyContent) return this.$emit('input', false)
      const form = { id, name, notice, applyContent: this.form.applyContent }
      this.$emit('update', form)
    },
  }
}
</script>

<style scoped lang="scss">
.header-btn{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 8px;
}
.sms-form{
    /* width:520px; */
    margin:8px auto 0 auto;
    .select-modules ::v-deep .el-form-item__content{
        display: flex;
        justify-content: space-between;
        .el-select{
            width:210px;
        }
        .el-form-item{
            margin-bottom:0;
        }
        &::before,&::after{
            display: none;
        }
    }
    &-content{
      margin-bottom: 0 !important;
      .textarea{
        ::v-deep .el-textarea__inner {
          border-bottom-left-radius: 0;
          border-bottom-right-radius: 0;
        }
      }
    }
     &-field{
      border-bottom: 1px solid #d9d9d9;
      border-left: 1px solid #d9d9d9;
      border-right:  1px solid #d9d9d9;
      padding: 5px 8px 5px 8px;
      background: #fff;
      border-bottom-left-radius: 4px;
      border-bottom-right-radius: 4px;
      clear: both;
      .insert-btn{
        font-size: 14px;
        color: $color-primary-light-6;
        margin-left: 12px;
      }
      .tip{
        float: right;
        color: #8C8C8C;
        font-size: 12px;
      }
    }
}
.tips{
    /* margin:50px auto 0; */
    width: 340px;
    height: 60px;
    font-size: 12px;
    font-weight: 400;
    color: #8C8C8C;
    line-height: 20px;
}
</style>
